﻿using DevExpress.XtraEditors;
using MesProjectWinform.Production.Common;
using MesProjectWinform.Production.Dto.Output.ProductionPlaning;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq; // 如果用Count()扩展方法
namespace MesProjectWinform.Production.Forms.ProductionPlaning
{
    public partial class ProductionPlaningForm : DevExpress.XtraEditors.XtraForm
    {
        public ProductionPlaningForm()
        {
            InitializeComponent();
        }

        private async void ProductionPlaningForm_Load(object sender, EventArgs e)
        {
            var tasks = await GetTasks();
            ganttControl1.DataSource = tasks;
            ganttControl1.KeyFieldName = "Id";
            ganttControl1.ParentFieldName = "ParentId";
            ganttControl1.ChartMappings.StartDateFieldName = "StartDate";
            ganttControl1.ChartMappings.FinishDateFieldName = "EndDate";
            ganttControl1.ChartMappings.ProgressFieldName = "Progress";
            ganttControl1.ChartMappings.TextFieldName = "DisplayText";

            // 只设置实际存在的列
            if (ganttControl1.Columns["LineCode"] != null)
            {
                ganttControl1.Columns["LineCode"].Caption = "产线编码";
                ganttControl1.Columns["LineCode"].Width = 120;
            }
            if (ganttControl1.Columns["LineName"] != null)
            {
                ganttControl1.Columns["LineName"].Caption = "产线名称";
                ganttControl1.Columns["LineName"].Width = 180;
            }
            // 隐藏其他所有列
            foreach (DevExpress.XtraTreeList.Columns.TreeListColumn col in ganttControl1.Columns)
            {
                if (col.FieldName != "LineCode" && col.FieldName != "LineName")
                    col.Visible = false;
            }

            // 只对子节点（工单）显示条，条颜色根据Status区分
            ganttControl1.CustomDrawTask += (s, args) =>
            {
                var isOrder = args.Node.GetValue("IsOrder");
                if (isOrder != null && !(bool)isOrder)
                {
                    args.Handled = true; // 不画父节点（产线）的条
                    return;
                }
                var status = args.Node.GetValue("Status")?.ToString();
                if (status == "正常")
                    args.Appearance.BackColor = Color.FromArgb(0, 200, 200);
                else if (status == "维修")
                    args.Appearance.BackColor = Color.Blue;
                else if (status == "委外")
                    args.Appearance.BackColor = Color.FromArgb(0, 180, 255);
            };

            // 默认展开所有节点
            ganttControl1.ExpandAll();

            // 表格美化（如有gridView1）
            var gridControl = this.Controls.Find("gridControl1", true).FirstOrDefault() as DevExpress.XtraGrid.GridControl;
            var gridView1 = gridControl?.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView1 != null)
            {
                gridView1.OptionsView.EnableAppearanceEvenRow = true;
                gridView1.Appearance.EvenRow.BackColor = Color.FromArgb(245, 249, 255);
                gridView1.Appearance.HeaderPanel.Font = new Font("微软雅黑", 11, FontStyle.Bold);
                gridView1.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gridView1.Appearance.Row.Font = new Font("微软雅黑", 10);
                gridView1.OptionsView.ShowGroupPanel = false;
                // 只对非复选框列设置只读
                foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView1.Columns)
                {
                    if (col.FieldName != "IsSelected" && col.FieldName != "选择")
                    {
                        col.OptionsColumn.AllowEdit = false;
                        col.OptionsColumn.ReadOnly = true;
                    }
                    else
                    {
                        col.OptionsColumn.AllowEdit = true;
                        col.OptionsColumn.ReadOnly = false;
                    }
                }
                gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
                gridView1.OptionsSelection.EnableAppearanceFocusedRow = true;
                gridView1.Appearance.FocusedRow.BackColor = Color.FromArgb(200, 230, 255);
                gridView1.Appearance.FocusedRow.ForeColor = Color.Black;
                gridView1.Appearance.SelectedRow.BackColor = Color.FromArgb(0, 120, 215);
                gridView1.Appearance.SelectedRow.ForeColor = Color.White;
                gridView1.Appearance.Row.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
                gridView1.RowHeight = 32;
                gridView1.Appearance.Row.BackColor = Color.White;
                gridView1.Appearance.Row.BorderColor = Color.FromArgb(230, 230, 230);
                gridView1.OptionsView.ShowHorizontalLines = DevExpress.Utils.DefaultBoolean.False;
                gridView1.OptionsView.ShowVerticalLines = DevExpress.Utils.DefaultBoolean.False;
                gridView1.OptionsView.ShowIndicator = false;
            }
            // 按钮美化（如有）
            foreach (var btnName in new[] { "simpleButton1", "simpleButton2", "simpleButton3" })
            {
                var btn = this.Controls.Find(btnName, true).FirstOrDefault() as DevExpress.XtraEditors.SimpleButton;
                if (btn != null)
                {
                    btn.Appearance.Font = new Font("微软雅黑", 10, FontStyle.Bold);
                    btn.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.UltraFlat;
                    btn.Appearance.BackColor = Color.FromArgb(240, 240, 240);
                    btn.Appearance.ForeColor = Color.Black;
                    btn.AppearanceHovered.BackColor = Color.FromArgb(0, 120, 215);
                    btn.AppearanceHovered.ForeColor = Color.White;
                    btn.AppearancePressed.BackColor = Color.FromArgb(0, 90, 180);
                    btn.AppearancePressed.ForeColor = Color.White;
                }
            }
        }
        // 1. GanttTask类重构
        public class GanttTask
        {
            public int Id { get; set; }
            public int? ParentId { get; set; }
            public string LineCode { get; set; }      // 产线编码
            public string LineName { get; set; }      // 产线名称
            public string OrderNo { get; set; }       // 工单号（仅工单有）
            public DateTime? StartDate { get; set; }
            public DateTime? EndDate { get; set; }
            public int? Progress { get; set; }
            public string Status { get; set; }        // 工单状态
            public int? Quantity { get; set; }
            public string DisplayText { get; set; }   // 工单条内显示内容
            public bool IsOrder { get; set; }         // 是否为工单（子节点）
            public int? Score { get; set; } // 新增分数字段
            public int? MaxScore { get; set; } // 新增满分字段
        }

        // 产线实体
        public class ProductionLine
        {
            /// <summary>
            /// 产线ID
            /// </summary>
            public long Id { get; set; }

            /// <summary>
            /// 产线名称
            /// </summary>
            public string Productionlinename { get; set; }

            /// <summary>
            /// 产线编号
            /// </summary>
            public string Productionlinecode { get; set; }

            /// <summary>
            /// 车间ID
            /// </summary>
            public string Workshopid { get; set; }

            /// <summary>
            /// 车间名称
            /// </summary>
            public string Workshopname { get; set; }

            /// <summary>
            /// 产线描述
            /// </summary>
            public string Productionlinedescription { get; set; }

            /// <summary>
            /// 产线属性
            /// </summary>
            public string Productionlineattributes { get; set; }

            /// <summary>
            /// 是否删除
            /// </summary>
            public bool IsDeleted { get; set; } = false;

            /// <summary>
            /// 创建人
            /// </summary>
            public string CreatedBy { get; set; }

            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime CreatedTime { get; set; } = DateTime.Now;

            /// <summary>
            /// 更新人
            /// </summary>
            public string UpdatedBy { get; set; }

            /// <summary>
            /// 更新时间
            /// </summary>
            public DateTime UpdatedTime { get; set; } = DateTime.Now;
        }

        // 工单实体
        public class WorkOrder
        {
            public decimal ID { get; set; }

            /// <summary>
            /// Desc:工单编码
            /// Default:
            /// Nullable:True
            /// </summary>           
            public string WORKORDERCODE { get; set; }

            /// <summary>
            /// Desc:工序编码
            /// Default:
            /// Nullable:True
            /// </summary>           
            public string PMID { get; set; }

            /// <summary>
            /// Desc:合格数
            /// Default:
            /// Nullable:True
            /// </summary>           
            public decimal? NUM { get; set; }

            /// <summary>
            /// Desc:不合格数量
            /// Default:
            /// Nullable:True
            /// </summary>           
            public decimal? NONUM { get; set; }

            /// <summary>
            /// Desc:排序
            /// Default:
            /// Nullable:True
            /// </summary>           
            public decimal? INDEX { get; set; }

            /// <summary>
            /// Desc:状态
            /// Default:
            /// Nullable:True
            /// </summary>           
            public bool ISSTATE { get; set; }

            /// <summary>
            /// Desc:显示状态
            /// Default:
            /// Nullable:True
            /// </summary>           
            public bool ISSHOW { get; set; }

            /// <summary>
            /// Desc:总数
            /// Default:
            /// Nullable:True
            /// </summary>           
            public decimal? SUM { get; set; }

            /// <summary>
            /// Desc:工序名称
            /// Default:
            /// Nullable:True
            /// </summary>           
            public string PMNAME { get; set; }

            /// <summary>
            /// Desc:是否开始
            /// Default:
            /// Nullable:True
            /// </summary>           
            public bool ISSTART { get; set; }

            /// <summary>
            /// Desc:时间冗余字段
            /// Default:
            /// Nullable:True
            /// </summary>           
            public string DATETIME { get; set; }

            /// <summary>
            /// Desc:产线ID
            /// Default:
            /// Nullable:True
            /// </summary>           
            public decimal? PRODUCTIONLINEID { get; set; }

            /// <summary>
            /// Desc:开始时间
            /// Default:
            /// Nullable:True
            /// </summary>           
            public DateTime? STARTETIME { get; set; }

            /// <summary>
            /// Desc:结束时间
            /// Default:
            /// Nullable:True
            /// </summary>           
            public DateTime? ENDTIME { get; set; }
            public int Quantity { get; set; } // 工单数量
        }

        private List<GanttTask> BuildGanttTasks(List<ProductionLine> lines, List<WorkOrder> orders)
        {
            var tasks = new List<GanttTask>();
            int idSeed = 1;
            var lineIdMap = new Dictionary<long, int>(); // 产线Id -> GanttTask.Id

            // 先加产线
            foreach (var line in lines)
            {
                tasks.Add(new GanttTask
                {
                    Id = idSeed,
                    LineCode = line.Productionlinecode,
                    LineName = line.Productionlinename,
                    IsOrder = false
                });
                lineIdMap[line.Id] = idSeed; // line.Id 是 long
                idSeed++;
            }

            // 再加工单
            foreach (var order in orders)
            {
                if (order.PRODUCTIONLINEID.HasValue)
                {
                    long productionLineId = (long)order.PRODUCTIONLINEID.Value;
                    if (lineIdMap.TryGetValue(productionLineId, out int parentId))
                    {
                        int progress = (order.SUM.HasValue && order.SUM.Value > 0)
                            ? (int)Math.Round((double)(order.NUM ?? 0) * 100.0 / (double)order.SUM.Value)
                            : 0;
                        tasks.Add(new GanttTask
                        {
                            Id = idSeed++,
                            ParentId = parentId,
                            OrderNo = order.WORKORDERCODE,
                            StartDate = order.STARTETIME,
                            EndDate = order.ENDTIME,
                            Score = order.NUM.HasValue ? (int)order.NUM.Value : 0,
                            MaxScore = order.SUM.HasValue ? (int)order.SUM.Value : 0,
                            Progress = progress,
                            Quantity = order.NUM.HasValue ? (int)order.NUM.Value : 0,
                            IsOrder = true,
                            DisplayText = $"{order.WORKORDERCODE} 分数:{order.NUM}/{order.SUM} 进度:{progress}% 数量:{order.NUM}"
                        });
                    }
                }
            }
            return tasks;
        }

        private async Task<List<GanttTask>> GetTasks()
        {
            // 模拟产线表
            var lines = new List<ProductionLine>
            {
                new ProductionLine { Id = 1, Productionlinecode = "aaa111", Productionlinename = "颗粒灌装线hhh" },
                new ProductionLine { Id = 2, Productionlinecode = "AE01", Productionlinename = "aa" },
                new ProductionLine { Id = 3, Productionlinecode = "BW1002", Productionlinename = "八维1002产线" },
                new ProductionLine { Id = 4, Productionlinecode = "GY001", Productionlinename = "颗粒灌装线(E)" },
                new ProductionLine { Id = 5, Productionlinecode = "KL001", Productionlinename = "颗粒灌装线" },
            };
            var response = await HttpClientHelper.RequestUrl(RequestType.Get, ProductionGolab.GetProductionLine, null);
            var result = JsonConvert.DeserializeObject<ApiResult<List<ProductionLine>>>(response);
            lines = result.Data;
            // 模拟工单表
            var orders = new List<WorkOrder>
            {
                new WorkOrder { ID = 1, PRODUCTIONLINEID = 1, WORKORDERCODE = "MO2025060209002", STARTETIME = new DateTime(2025,8,28), ENDTIME = new DateTime(2025,9,7), NUM = 10, SUM = 20, Quantity = 2 },
                new WorkOrder { ID = 2, PRODUCTIONLINEID = 1, WORKORDERCODE = "MO202509080001", STARTETIME = new DateTime(2025,9,8), ENDTIME = new DateTime(2025,9,12), NUM = 18, SUM = 30, Quantity = 10 },                                                                       
                new WorkOrder { ID = 3, PRODUCTIONLINEID = 2, WORKORDERCODE = "MO202508010001", STARTETIME = new DateTime(2025,8,29), ENDTIME = new DateTime(2025,9,5), NUM = 25, SUM = 50, Quantity = 5 },                                                                        
                new WorkOrder { ID = 4, PRODUCTIONLINEID = 3, WORKORDERCODE = "MO202509020001", STARTETIME = new DateTime(2025,9,2), ENDTIME = new DateTime(2025,9,10), NUM = 60, SUM = 80, Quantity = 8 },                                                                        
                new WorkOrder { ID = 5, PRODUCTIONLINEID = 3, WORKORDERCODE = "MO202509110002", STARTETIME = new DateTime(2025,9,11), ENDTIME = new DateTime(2025,9,15), NUM = 100, SUM = 100, Quantity = 12 },                                                              
                new WorkOrder { ID = 6, PRODUCTIONLINEID = 4, WORKORDERCODE = "MO202509050001", STARTETIME = new DateTime(2025,9,5), ENDTIME = new DateTime(2025,9,18), NUM = 5, SUM = 20, Quantity = 20 },                                                              
                new WorkOrder { ID = 7, PRODUCTIONLINEID = 5, WORKORDERCODE = "MO202509070001", STARTETIME = new DateTime(2025,9,7), ENDTIME = new DateTime(2025,9,20), NUM = 45, SUM = 1000, Quantity = 15 },
            };
            var respons = await HttpClientHelper.RequestUrl(RequestType.Get, ProductionGolab.GetWorkProcesss, null);
            var resul = JsonConvert.DeserializeObject<ApiResult<List<WorkOrder>>>(respons);
            orders = resul.Data;
            return BuildGanttTasks(lines, orders);
        }
    }
}